package com.lz.sports.utils

import android.text.TextUtils
import com.lz.library.extension.APP
import com.lz.sports.bean.DeviceInfo
import com.lz.ub.core.UBCScanResult
import java.io.BufferedReader
import java.io.InputStreamReader

//扫描出来的最大字符长度
const val MAX_NAME_LENGTH = 14

fun sub(str: String): String = if (str.length <= MAX_NAME_LENGTH) str else str.substring(0, MAX_NAME_LENGTH)

fun UBCScanResult.toDeviceInfo(projectId: Int, hasBinding: Boolean): DeviceInfo {
    return DeviceInfo().also {
        it.projectId = projectId
        it.mac = this.mac;
        it.name = sub(this.name)
        it.rssi = this.rssi;
        it.hasBinding = hasBinding
    }
}

//R.array....
fun Int.toArrayList(): ArrayList<String> = ArrayList(APP.resources.getStringArray(this).toList())

//十六进制数据和无进位校验
private fun hexAddCode(hex: String): String {
    if ((hex.length and 1) == 1) return ""
    return try {
        var num: Int = 0
        for (index in hex.indices step 2) {
            num += Integer.parseInt(hex.substring(index, index + 2), 16)
        }
        Integer.toHexString(num and 0xFF).uppercase()
    } catch (_: Exception) {
        ""
    }
}

fun hexCheckCode(hex: String): String = "$hex${hexAddCode(hex)}"

//将asserts中的文件转成bean
inline fun <reified T> readAssetsBean(fileName: String): T? {
    val json = readAssetsText(fileName)
    if (!TextUtils.isEmpty(json)) return json.jsonToBean()
    return null
}

//将asserts中的文件转成bean
inline fun <reified T> readAssetsList(fileName: String): List<T> {
    val json = readAssetsText(fileName)
    if (!TextUtils.isEmpty(json)) return json.jsonToList()
    return emptyList()
}

//读取asserts中的配置文件
fun readAssetsText(fileName: String): String {
    val sb = StringBuilder()
    try {
        APP.resources.assets.open(fileName).use { ism ->
            BufferedReader(InputStreamReader(ism)).useLines { sequenceStr ->
                sequenceStr.iterator().forEach { sb.append(it) }
            }
        }
    } catch (_: Exception) {
    }
    return sb.toString()
}